/*
 * @Author: zhangyu
 * @Date: 2021-01-15 18:02:15
 * @LastEditTime: 2021-02-05 11:06:00
 */
const BaseController = require('./BaseController.js');

class UserController extends BaseController {
  // 登录
  async user_login(){
	  const { ctx } = this
    let params = await this.getParams(ctx)
    let result = await ctx.service.user.login(params)
    // 判断
    if(result.code == 64){
      // 生成token
      let token = ctx.helper.getToken()
      // 存入redis
      ctx.helper.redisSet(token,{
        id: result.data.id,
        role_id: result.data.role_id,
        name: result.data.name
      },1800)
      this.showSuccess({
        token,
        name: result.data.name,
        avatar: result.data.avatar,
        menu: result.data.menu
      },'登录成功')
    }else{
      this.ApiException(result.msg)
    }
  }

  // 退出登录
  user_logout(){
    const { ctx } = this
    ctx.helper.redisDelete(ctx.request.header.token)
    this.showSuccess([],'退出登录成功')
  }

  // 获取权限
  async user_auth(){
    const { ctx } = this
    let user = await ctx.helper.getUser()
    if(user){
      let result = await ctx.service.user.getAuth(JSON.parse(user).role_id)
      this.showSuccess(result)
    }
  }

  // 用户列表
  async user_list(){
    const { ctx } = this
    let params = await this.getParams(ctx)
    let result = await ctx.service.user.list(params)
	  this.showSuccess(result)
  }

  // 删除用户
  async user_delete(){
    const { ctx } = this
    let params = await this.getParams(ctx)
    let result = await ctx.service.user.deleteItem(params)
	  this.showSuccess(result)
  }

  // 创建用户
  async user_create(){
    const { ctx } = this
    let params = await this.getParams(ctx)
    let result = await ctx.service.user.create(params)
    if(result){
      this.showSuccess(result)
    }else{
      this.ApiException('该账号已存在')
    }
  }

  // 编辑用户
  async user_edit(){
    const { ctx } = this
    let params = await this.getParams(ctx)
    let result = await ctx.service.user.edit(params)
    this.showSuccess(result)
  }

  // 重置密码
  async reset_password(){
    const { ctx } = this
    let params = await this.getParams(ctx)
    let result = await ctx.service.user.resetPassword(params)
    this.showSuccess(result)
  }
}

module.exports = UserController;